package com.tangdi.mkfile.gzffmx;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.tangdi.ReportFileInfo;
import com.tangdi.Utils;
import com.tangdi.Bean.CZGZ_DWCOUNT;
import com.tangdi.Bean.CZGZ_GZLB;
import com.tangdi.Bean.CZGZ_SJGZ;
import com.tangdi.Bean.CZGZ_ZGGZMX;
import com.tangdi.Bean.XM_BM_XM_MC;
import com.tangdi.Dao.impl.GongziMXImpl;

public class CreateGZFFMXPDF_ByDW {
	private Logger logger = Logger.getLogger(CreateGZFFMXPDF_ByDW.class);
	String pdf_url_root = Utils.getFilePath("root_path");
	private String folder_Name = ReportFileInfo.FOLDER_NAME_GZTIAO.getName();
	private String file_Type = "pdf";
	private String file_name_type = ReportFileInfo.FILE_NAME_GZTIAO.getName();
	private Font FontChinese;
	public int createPDF(Map<String,List<XM_BM_XM_MC>> map_bm_mc_list,List<CZGZ_DWCOUNT> listDWCOUNT,List<CZGZ_GZLB> list_gz_lb,String month) {
		StringBuffer sql_select = null;
		Map<String,String> map_lb_select = new HashMap<String,String>();
		int initSize = 0;
		int width = 30;
		
		for(int i=0; i < map_bm_mc_list.size(); i++){//组装工资明细查询sql
			sql_select = new StringBuffer("SELECT TRIM(YF) AS YF, TRIM(NME) AS NME, ");
			List<XM_BM_XM_MC> list_BM_MC = map_bm_mc_list.get(list_gz_lb.get(i).getLB_BM());
			if(initSize < list_BM_MC.size()){//算出最长列
				initSize = list_BM_MC.size();
			}
			for(int j=0; j < list_BM_MC.size(); j++){
				sql_select.append("coalesce(TO_CHAR(to_number("+ list_BM_MC.get(j).getXM_BM() +"),'9999,999,999,990.00'),'0.00') AS " +list_BM_MC.get(j).getXM_BM() + ",");
			}
			map_lb_select.put(list_gz_lb.get(i).getLB_BM(), sql_select.substring(0, sql_select.length() - 1));
		}
		
		initSize = initSize + 3;
		float[] cellWidths = new float[initSize];
		for(int a = 0; a < initSize; a++){
			cellWidths[a] = width;
	    }
		cellWidths[0] = 20;
		cellWidths[1] = 22;
		
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    try {
	    	BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
	        //使用Windows系统字体(MSYH)
	        //BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/MSYH.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
	        //使用Windows系统字体(SIMYOU)
	        //BaseFont bfChinese = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
	        //FontChinese = new Font(bfChinese, 8, Font.NORMAL);
	        FontChinese = new Font(bfChinese, 7, Font.NORMAL);
			Document document = null;
			PdfPTable table = null;
			String pdf_url = "";
			GongziMXImpl gzmx = new GongziMXImpl();
			
			//listDWCOUNT.size()
			for(int i = 0; i < listDWCOUNT.size(); i++){
				logger.info("单位名称：" + listDWCOUNT.get(i).getDW_MC() + " | 单位类别：" + listDWCOUNT.get(i).getGZ_LB_DM());
				if(i == 0){
					pdf_url = pdf_url_root + "/" + month + "/" + file_Type + "/" + folder_Name + "/" + month + "_"+ file_name_type + "_" + listDWCOUNT.get(i).getDW_DM() +"_" + listDWCOUNT.get(i).getDW_MC() + ".pdf";
					//document = new Document(PageSize.A3,0,0,0,0);
					//document = new Document(new RectangleReadOnly(1020F, 791F),0,0,0,0);
					document = new Document(new RectangleReadOnly(920F, 790F),0,0,0,0);
					//在填写文件路径时，一定要写上具体的文件名称（xx.txt），否则会出现拒绝访问。
					File file = new File(pdf_url);
					if(!file.exists()){
					    //先得到文件的上级目录，并创建上级目录，在创建文件
						file.getParentFile().mkdirs();
						file.createNewFile();
					}
			        PdfWriter.getInstance(document, new FileOutputStream(pdf_url)); 
					PdfWriter.getInstance(document, baos); 
					document.open();
				}else{
					if(listDWCOUNT.get(i).getDW_DM().equals(listDWCOUNT.get(i-1).getDW_DM())){
						if(!listDWCOUNT.get(i).getGZ_LB_DM().equals(listDWCOUNT.get(i-1).getGZ_LB_DM())){
							document.newPage();
						}
					}
				}
				String gz_lb = listDWCOUNT.get(i).getGZ_LB_DM();
				String gz_dw_dm = listDWCOUNT.get(i).getDW_DM();
				
				int sj_Size = Integer.valueOf(map_bm_mc_list.get(gz_lb).size()) + 3;
				
				//document.add(new Paragraph(""+listDWCOUNT.get(i).getDW_MC(),FontChinese));
				table = new PdfPTable(cellWidths);
				//***************表连续不分页，至关重要的作用 
				//table.setKeepTogether(true);
				
				table.setTotalWidth(initSize * width);
				//table.setSpacingBefore(3f);
				//table.getDefaultCell().setMinimumHeight(35);
				//工资明细list
				List<CZGZ_ZGGZMX> listmx=new ArrayList<CZGZ_ZGGZMX>();
				
				List<XM_BM_XM_MC> list_MX_BM_MC = map_bm_mc_list.get(listDWCOUNT.get(i).getGZ_LB_DM());
				listmx = gzmx.listGZMXReportByLB(month, gz_dw_dm, gz_lb,list_MX_BM_MC, map_lb_select.get(gz_lb));

				int listmx_size = listmx.size(); //行数
				for(int j = 0; j < listmx.size(); j++){
					//int yuShu = listmx_size % 15; //取余数

					CZGZ_ZGGZMX gz_mx = listmx.get(j);
					
					if((j + 1) % 15 == 1){ //每页table第一行  显示单位名称
						table.addCell(getCell_dwmc(listDWCOUNT.get(i).getDW_MC(), initSize, 1));
					}
					//列名--start
					table.addCell(getCell_Name("序号",1,1));
					table.addCell(getCell_Name("月份",1,1));
					table.addCell(getCell_Name("姓名",1,1));
					for(int h = 0; h < list_MX_BM_MC.size(); h++){//显示工资科目名称
						table.addCell(getCell_Name(list_MX_BM_MC.get(h).getXM_MC(),1,1));
						}
					if(sj_Size < initSize){
						for(int a = 0; a < (initSize - sj_Size); a++){
							table.addCell(getCell_Name("",1,1));
						}
					}
					//列名--end
					
	                //列值 --start
					table.addCell(getCell_Value(String.valueOf(j + 1),1,1));
					table.addCell(getCell_Value(gz_mx.getYF().substring(2, 4) + "-" +gz_mx.getYF().substring(4, 6),1,1));
					table.addCell(getCell_Value(gz_mx.getNME(),1,1));
					for(int k = 0; k < list_MX_BM_MC.size(); k++){//根据工资类别反射查找工资科目
						String gz_value = (String)Utils.getFieldReflect(gz_mx,CZGZ_ZGGZMX.class,list_MX_BM_MC.get(k).getXM_BM());
						
						table.addCell(getCell_Value(((gz_value.trim()).equals("0.00")  ? " " : (gz_value.trim())),1,1));
						}
					if(sj_Size < initSize){
						for(int b = 0; b < (initSize - sj_Size); b++){
							table.addCell(getCell_Value("",1,1));
						}
					}
					if((j + 1) % 15 == 0){//每页table 最后一行
						table.addCell(getCell_dw_end("", initSize, 1));
					}
					//列值 --end
					//补充，如果列数不是15的倍数 后补空行 凑满一页， 为 防止：不同单位员工 工资条显示在同一页 或 同单位不同工资类别显示在同一页
					if((j + 1) == listmx_size){
						/*if(yuShu != 0){
							for(int mb = 0; mb < (15 - yuShu); mb++){
								table.addCell(getCell_Name("",initSize,1));
								table.addCell(getCell_Value("",initSize,1));
								
								if((mb + 1) == (15 - yuShu)){
									table.addCell(getCell_dwmc("",initSize,1));
								}
							}
						}*/
						document.newPage();
					}
				}
				
				table.setWidthPercentage(100); // 设置表格宽度
		    	document.add(table);
		    	
				if(i == (listDWCOUNT.size() - 1)){
					document.close();
				}else{
					if(!(listDWCOUNT.get(i).getDW_DM()).equals(listDWCOUNT.get(i+1).getDW_DM())){
						document.close();
						//document = new Document(PageSize.A3,0,0,0,0);
						document = new Document(new RectangleReadOnly(920F, 790F),0,0,0,0);
						pdf_url = pdf_url_root + "/" + month + "/" + file_Type + "/" + folder_Name + "/" + month + "_"+ file_name_type + "_" + listDWCOUNT.get(i + 1).getDW_DM() +"_" + listDWCOUNT.get(i + 1).getDW_MC() + ".pdf";
						//在填写文件路径时，一定要写上具体的文件名称（xx.txt），否则会出现拒绝访问。
						File file = new File(pdf_url);
						if(!file.exists()){
						    //先得到文件的上级目录，并创建上级目录，在创建文件
							file.getParentFile().mkdirs();
							file.createNewFile();
						}
				        PdfWriter.getInstance(document, new FileOutputStream(pdf_url)); 
						PdfWriter.getInstance(document, baos); 
						document.open();
					}
				}
				
			}
	    } catch (Exception e) {
	    	e.printStackTrace();
	    	return -1;
		}
	    return 0;
	}

	private PdfPCell getCell_Name(String cellValue, int colspan, int rowSpan) {
	    PdfPCell cell = new PdfPCell();
	    try {
	        cell = new PdfPCell(new Phrase(cellValue, FontChinese));
	        cell.setRowspan(rowSpan);
	        cell.setColspan(colspan);
	        cell.setFixedHeight(27.00F);
	        cell.setBorder(0);
	        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
	        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return cell;
	}
	private PdfPCell getCell_Value(String cellValue, int colspan, int rowSpan) {
	    PdfPCell cell = new PdfPCell();
	    try {
	        cell = new PdfPCell(new Phrase(cellValue, FontChinese));
	        cell.setRowspan(rowSpan);
	        cell.setColspan(colspan);
	        cell.setFixedHeight(21.40F);
	        cell.setBorder(0);
	        cell.setVerticalAlignment(Element.ALIGN_TOP);
	        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return cell;
	}	
	private PdfPCell getCell_dwmc(String cellValue, int colspan, int rowSpan) {
	    PdfPCell cell = new PdfPCell();
	    try {
	        cell = new PdfPCell(new Phrase(cellValue, FontChinese));
	        cell.setRowspan(rowSpan);
	        cell.setColspan(colspan);
	        cell.setFixedHeight(30.50F);
	        cell.setBorder(0);
	        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
	        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return cell;
	}
	private PdfPCell getCell_dw_end(String cellValue, int colspan, int rowSpan) {
	    PdfPCell cell = new PdfPCell();
	    try {
	        cell = new PdfPCell(new Phrase(cellValue, FontChinese));
	        cell.setRowspan(rowSpan);
	        cell.setColspan(colspan);
	        cell.setFixedHeight(20.00F);
	        cell.setBorder(0);
	        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
	        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return cell;
	}
	public static void main(String[] args) {
		//年月
		String month = "201905";
		List<CZGZ_DWCOUNT> listDWCOUNT=new ArrayList<CZGZ_DWCOUNT>();
		GongziMXImpl gz_dw_count = new GongziMXImpl();
		listDWCOUNT = gz_dw_count.listGZDWCount(month);	
		
		//工资类别，科目项信息
		Map<String,List<XM_BM_XM_MC>> map_bm_mc_list = new HashMap<String,List<XM_BM_XM_MC>>();
		//工资类别list
		List<CZGZ_GZLB> listlb=new ArrayList<CZGZ_GZLB>();
		GongziMXImpl gzlb = new GongziMXImpl();
		listlb = gzlb.listGZLBReport(month);	
		//实际工资科目 按工资类别
		List<CZGZ_SJGZ> list_sjgz=new ArrayList<CZGZ_SJGZ>();
		GongziMXImpl sjgz = new GongziMXImpl();
		list_sjgz = sjgz.listSJGZReport(month);	
		
		//组装工资类别 ，实际工资科目项，对应好关系；方便后续使用
		for(int i=0;i<listlb.size();i++){
			List<XM_BM_XM_MC> bm_mc_list = new ArrayList<XM_BM_XM_MC>();
			for(int j=0; j<list_sjgz.size(); j++){
				XM_BM_XM_MC bm_mc= new XM_BM_XM_MC();
				if((listlb.get(i).getLB_BM().trim()).equals(list_sjgz.get(j).getGZ_LB().trim())){
					bm_mc.setXM_BM(Utils.getXM_BM(list_sjgz.get(j).getXM_BM().trim()));
					bm_mc.setXM_MC(list_sjgz.get(j).getXM_MC().trim());
	
					bm_mc_list.add(bm_mc);
				}
			}
			map_bm_mc_list.put(listlb.get(i).getLB_BM().trim(), bm_mc_list);
		}
		
		CreateGZFFMXPDF_ByDW c = new CreateGZFFMXPDF_ByDW();
	    c.createPDF(map_bm_mc_list,listDWCOUNT,listlb,month);
	    System.out.println("制作完成");
	}
}
